﻿#include "include/framework.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <thread>
#include <map>
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
HHOOK g_hMouseHook = NULL;
HWND hWd;
NOTIFYICONDATA g_nid;
// 全局变量
HWND g_hWnd;
HICON g_hIcon;
std::string ct;
std::map<std::string, std::string> config;
std::map<std::string, std::string> read_config(const std::string& filename) {
    std::map<std::string, std::string> config;
    std::ifstream file(filename);
    std::string line;
    std::string key;

    if (file.is_open()) {
        while (getline(file, line)) {
            std::istringstream is_line(line);
            std::string key;
            if (getline(is_line, key, '=')) {
                std::string value;
                if (getline(is_line, value)) {
                    config[key] = value;
                }
            }
        }
        file.close();
    }
    else
    {
        MessageBox(NULL, L"[37] config.ini文件不存在", L"错误", MB_OK | MB_ICONERROR);
        exit(0);
    }
    return config;
}

void closeW(HINSTANCE hInstance)
{
    POINT Cp;
    int X, Y;
    while (true)
    {
        GetCursorPos(&Cp);
        X = Cp.x;
        Y = Cp.y;
        printf("%d-%d\n", X, Y);
        Sleep(22);
    }

}
/************************************************
*
* 计算鼠标是否点击当前窗口区域类
* 4    8
*   24  28
**/
bool ifGetWIndowArea(int x, int y, int flag)
{
    RECT rc;
    if (hWd != NULL) {
        // 获取窗口客户区的矩形区域
        GetClientRect(hWd, &rc);
        POINT ptLT = { rc.left, rc.top };
        POINT ptRB = { rc.right, rc.bottom };
        ClientToScreen(hWd, &ptLT);
        ClientToScreen(hWd, &ptRB);
        if (flag == 0)
        {
            if (x > ptLT.x && x< ptRB.x && y>ptLT.y && y < ptRB.y + 222)
            {
                return true;
            }
        }
        else {
            if (x > ptLT.x && x< ptRB.x && y>ptLT.y && y < ptRB.y + 222)
            {
                return true;
            }
        }

        return false;
    }
}
std::wstring StringToLPCWSTR(const std::string& str) {
    int size_needed = MultiByteToWideChar(CP_ACP, 0, str.c_str(), int(str.size()), NULL, 0);
    std::wstring wstr(size_needed, 0);
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), int(str.size()), &wstr[0], size_needed);
    return wstr;
}
LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    POINT Cp;
    int X, Y;
    if (nCode == HC_ACTION) {
        switch (wParam) {
        case WM_LBUTTONDOWN:
            GetCursorPos(&Cp);
            X = Cp.x;
            Y = Cp.y;
            if (!ifGetWIndowArea(X, Y, 0))
            {
                ShowWindow(hWd, SW_MINIMIZE);
                //PostMessage(hWd, WM_CLOSE, 0, 0);
            }
            break;
        case WM_RBUTTONDOWN:
            GetCursorPos(&Cp);
            X = Cp.x;
            Y = Cp.y;
            if (!ifGetWIndowArea(X, Y, 1))
            {
                ShowWindow(hWd, SW_MINIMIZE);
                //PostMessage(hWd, WM_CLOSE, 0, 0);
            }
            break;
        }

    }
    return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
}
int main()
{
    std::ifstream file("load.js");
    if (!file.is_open()) {
        MessageBox(NULL, L"[127] load.js文件缺失", L"错误", MB_OK | MB_ICONERROR);
        return 0;
    }
    std::string content((std::istreambuf_iterator<char>(file)),
    std::istreambuf_iterator<char>());
    file.close();
    ct = content;
  
    config = read_config("config.ini");
    if ("" == config["url"])
    {
        MessageBox(NULL, L"配置文件错误", L"提示", MB_OK|MB_ICONERROR);
        exit(0);
    }
    //ShowWindow(FindWindow(L"Shell_TrayWnd", NULL), SW_SHOW);
    HWND hwndc = FindWindow(L"Shell_TrayWnd", NULL);
    HDC hdc = GetDC(NULL);
    int cx = GetDeviceCaps(hdc, DESKTOPHORZRES);
    int cy = GetDeviceCaps(hdc, DESKTOPVERTRES);
    ReleaseDC(NULL, hdc);
    POINT cursorPos;
    GetCursorPos(&cursorPos);
    int x = cursorPos.x;
    int y = cursorPos.y;
    WNDCLASSEXW wcex;
    HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = FALSE;
    wcex.lpszClassName = L"test";
    wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    if (!RegisterClassExW(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Windows Desktop Guided Tour"),
            MB_ICONERROR);

        return 1;
    }
    HWND hWnd = CreateWindow(
        L"test",
        NULL,
        WS_POPUP,
        /*WS_OVERLAPPEDWINDOW, **/
        CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
        nullptr, nullptr, hInstance, nullptr);

    if (!hWnd)
    {
        return FALSE;
    }

    //std::thread t(closeW, hInstance);
    //t.join();
    ShowWindow(hWnd, SW_SHOW);
    UpdateWindow(hWnd);
    RECT rect2;
    float rate = 0;
    int start = x - ((cx * 0.2) / 2) <= 0 ? 0 : x - ((cx * 0.2) / 2);

    if (GetClientRect(hwndc, &rect2)) {
        // 获取任务栏高度
        int taskbarHeight = GetSystemMetrics(SM_CYSCREEN) - rect2.bottom;
        printf("%d", rect2.bottom);
        SetWindowPos(hWnd, HWND_TOPMOST, start, (taskbarHeight - taskbarHeight * 0.9) - 5, cx * 0.2, taskbarHeight * 0.9, SWP_SHOWWINDOW);
    }


    ShowWindow(hWnd, SW_HIDE);
    AnimateWindow(hWnd, 100, AW_VER_NEGATIVE);



    // <-- WebView2 sample code starts here -->
    CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr, Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
        [hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
            // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
            env->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
                [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
                    if (controller != nullptr) {
                        webviewController = controller;
                        webviewController->get_CoreWebView2(&webviewWindow);
                    }
                    // Add a few settings for the webview
                    // The demo step is redundant since the values are the default settings
                    wil::com_ptr<ICoreWebView2Settings> settings;
                    webviewWindow->get_Settings(&settings);
                    settings->put_IsScriptEnabled(TRUE);
                    settings->put_AreDefaultScriptDialogsEnabled(TRUE);
                    settings->put_IsWebMessageEnabled(TRUE);

                    // Resize WebView to fit the bounds of the parent window
                    RECT bounds;
                    GetClientRect(hWnd, &bounds);
                    webviewController->put_Bounds(bounds);
                    // Schedule an async task to navigate to Bing  >
                    webviewWindow->Navigate(StringToLPCWSTR(config["url"]).c_str());

                    //--script
                    webviewWindow->ExecuteScript(StringToLPCWSTR(ct).c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
                        [](HRESULT error, LPCWSTR result)->HRESULT {
                            if (error != S_OK) {

                            }
                            LPCWSTR URL = result;
                            return S_OK;
                        }).Get());
                    //--end script
                    return S_OK;
                }).Get());
            return S_OK;
        }).Get());

    HINSTANCE hs = GetModuleHandle(NULL);
    g_hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, hs, 0);
    // <-- WebView2 sample code ends here -->
    MSG msg;

    while (GetMessage(&msg, nullptr, 0, 0))
    {

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return (int)msg.wParam;
}


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    hWd = hWnd;
    switch (message)
    {

    case WM_SIZE:
    {
        if (webviewController != nullptr) {
            RECT bounds;
            GetClientRect(hWnd, &bounds);
            webviewController->put_Bounds(bounds);
        };
        break;
    }
    case WM_COMMAND:
    {


        int wmId = LOWORD(wParam);
        // 分析菜单选择:
        switch (wmId)
        {
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        break;
    }
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        // TODO: 在此处添加使用 hdc 的任何绘图代码...
        EndPaint(hWnd, &ps);
        break;
    }
    case WM_CLOSE:
    {
        //  PostAppMessage(hWnd, WM_CLOSE, 0, 0);
        exit(0);
        break;
    }

    default: {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    }
    return 0;
}